import { Component, OnInit } from '@angular/core';

import { InfiniteScrollCustomEvent } from '@ionic/angular';

import { Router } from '@angular/router';
import * as Parse from "parse"
(Parse as any).serverURL = "http://metapunk.cn:9999/parse"
Parse.initialize("dev")

@Component({
  selector: 'app-waterfall',
  templateUrl: './waterfall.component.html',
  styleUrls: ['./waterfall.component.scss']
})
export class WaterfallComponent implements OnInit{
  MediumData: any = []
  text: string[] = [];
  MediumDataTemp: any = []
  //用于存放搜索出来的数据
  MediumDataSearch: any = []
  inSearch: boolean = false;
  querySearch: string = ""
  textTemp: string[] = []
  resultsTemp: string[] = []

  ngOnInit() {
    this.generateCard();
  }
  public results = [...this.text];
  handleClear() {
    this.inSearch = true;
    this.MediumData = this.MediumDataTemp
  }
  handleInput(event: any) {
    this.inSearch = true;
    this.querySearch = event.target.value.toLowerCase()
    if (!this.querySearch) {
      this.handleClear();
      return
    }
    this.results = this.text.filter((d) => d.toLowerCase().indexOf(this.querySearch) > -1);
    this.MediumDataTemp = this.MediumData
    this.MediumDataSearch = []
    for (let medium of this.MediumData) {
      for (let t of this.results) {
        if (medium.get("text") == t) {
          this.MediumDataSearch.push(medium)
          break;//第一次找到一个一样的即可
        }
      }
    }
    this.MediumData = this.MediumDataSearch;
  }

  async generateCard() {
    if (!this.inSearch) {
      let query = new Parse.Query("BRBMedium");
      query.limit(10)
      query.include("user")
      let mediumList: any = await query.find();
      Array.prototype.push.apply(this.MediumData, mediumList);
      this.text = []
      for (let medium of this.MediumData) {
        this.text.push(medium.get('text'))

      }
    } else {
      let MediumDataSearchTemp: any = []
      let query = new Parse.Query("BRBMedium");
      query.limit(10)
      query.include("user")
      let mediumList2: any = await query.find();
      for (let medium of mediumList2) {
        this.textTemp.push(medium.get('text'))
        this.resultsTemp = this.textTemp.filter((d) => d.toLowerCase().indexOf(this.querySearch) > -1);
        for (let t of this.resultsTemp) {
          if (medium.get("text") == t) {
            MediumDataSearchTemp.push(medium)
            break;
          }
        }
      }
      Array.prototype.push.apply(this.MediumData, MediumDataSearchTemp);
      console.log(this.MediumData)
    }
  }
  onIonInfinite(ev: any) {
    this.generateCard();
    setTimeout(() => {
      (ev as InfiniteScrollCustomEvent).target.complete();
    }, 300);
  }

  constructor(private router: Router) {
    this.MediumData = [
    ]
  }


  goDetail(mediumId: string,userId:string) {
    this.router.navigate(["/BigRedBook/home/detail"], {
      queryParams: {mediumId,userId}
    }
    );
  }
}
